package com.example.excelreader.controller;

import com.example.excelreader.service.ExcelReadService;
import com.example.excelreader.util.ExcelUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.Assert;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

@Slf4j
@RestController
@RequestMapping("/excel")
public class ExcelReadController {

    @Autowired
    private ExcelReadService excelReadService;

    // 访问路径 localhost:8080/excel/read 方式POST
    @PostMapping("/read")
    public String readExcel(@RequestParam("excel") MultipartFile file){
        Assert.state(file != null && !file.isEmpty(), "file is empty");
        int size = 0;
        log.info("接收到文件[{}]，大小为:[{}]bytes", file.getOriginalFilename(), file.getSize());
        try {
            ExcelUtil.checkSuffix(file.getOriginalFilename());
            size = excelReadService.read(file.getInputStream());
        }catch (Exception e){
            log.error("文件读取失败:[{}]", e.getMessage(), e);
        }
        return "共插入[" + size + "]条数据";
    }

}
